﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.MBSM.BLL;
using Grove.ORM;
using HZ.MBSM.Model;
using HZ.MBSM.DBUtility;

public partial class Bidder_GoodsBidAc : System.Web.UI.Page
{
    string _strAccount_TBR, _strProjectId, _strCompanySort, _strAccountId_SC;
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
        _AccountType.Add(HZ.MBSM.DAL.AccountType.enumCompany);
        if (HZ.MBSM.BLL.Login.CheckAssert(_AccountType))
        {
            _strProjectId = SysFun.ToTrim(SysFun.IsSQL(Request.QueryString["projectid"]));
            _strAccountId_SC = SysFun.ToTrim(SysFun.IsSQL(Request.QueryString["accountid_sc"]));
            if (_strAccountId_SC == "" || _strProjectId == "")
            {
                return;
            }
            _strAccount_TBR = SysFun.ToTrim(((HZ.MBSM.Model.Account)Session["Account"]).AccountId);
            _strCompanySort = ((HZ.MBSM.Model.Account)Session["Account"]).Sort;
            String _strStatus = "";
            Db db = new Db();
            System.Data.IDataReader dr;

            //判断是否能投标之投标人没有投标权限
            string SQL = "select BiddingSwitching From ProjectCompanyAttribution where accountid=" + _strAccount_TBR + " and projectid=" + _strProjectId;
            dr = db.DataReader(SQL);
            while (dr.Read())
            {
                _strStatus = SysFun.ToTrim(dr["BiddingSwitching"].ToString());
            }
            dr.Close();
            dr.Dispose();
            db.Close();

            if (_strStatus == "")
            {
                Response.Write("<script>window.alert('对不起，您的企业没有投标权限,如想投标请与招标中心联系！');</script>");
                Response.Write("<script>window.location=\"Nothing.aspx?Projectid=" + _strProjectId + "\"</script>");
                return;
            }
            else if (_strStatus == "0")
            {
                Response.Write("<script>window.alert('对不起,投标开关没开或已关闭,具体投标时间请与招标中心联系！');</script>");
                Response.Write("<script>window.location=\"Nothing.aspx?Projectid=" + _strProjectId.ToString() + "\"</script>");
                return;
            }
            if (Request.Form["submitbid"] == "投 标")
            {
                submitbid();
            }

         
            showGridView();

        }
    }

    protected void GridView1_DataBound(object sender, EventArgs e)
    {
        BackBid();
    }

    private void BackBid()
    {
        string s = "";
        foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                if (row.Cells[12].Text.ToString() == "1")//是否投标
                {
                    s += "@" + row.Cells[0].Text;//药品流水号
                }
            }
        }

        if (!txtdatabase.Value.Contains(s))
       
        {
            txtdatabase.Value += s;
            txtmsg.Value += s;
            msg.Text += s;
        }
    }

    public void showGridView()
    {
        string _strGoodsId = txtGoodsId.Text.ToString();
        string _strWhere = fctConditions();
        Db db = new Db();
        DbPage dbPage = new DbPage(db);
        //dbPage.Table = GBAstrtable;                                               //要查询的表明
        dbPage.Table = " v_Product_goods INNER JOIN" +

                       " bid_goods_tbr ON bid_goods_tbr.goodsid=v_Product_goods.goodsid and v_Product_goods.AccountId_SC = bid_goods_tbr.AccountId_SC inner join" +//投标表
                       " bid_project_product ON " +
                       " v_Product_goods.ProductId = bid_project_product.ProductId and bid_goods_tbr.projectid=bid_project_product.projectid LEFT OUTER JOIN" +
                       " (select goodsid,1 as num from Project_Bid where projectid=" + _strProjectId + " and AccountId=" + _strAccount_TBR + ") a ON v_Product_goods.GoodsId = a.GoodsId";                                               //要查询的表明
        dbPage.Key = "v_Product_goods.goodsid";                                               //表的主键    
        dbPage.Where = _strWhere;                                           //查询条件    
        dbPage.SelectField = "v_Product_goods.GoodsId, v_Product_goods.Productid, v_Product_goods.ProductName, v_Product_goods.Outlookc,  v_Product_goods.Medicinemodel,  CompanyName, v_Product_goods.Factor,v_Product_goods.Unit, v_Product_goods.LicenseNumber, v_Product_goods.UserCode, v_Product_goods.GoodsName,CASE v_Product_goods.QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + " END  AS QualityLevels,a.num";//要显示的字段
        dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
        dbPage.PageSize = 25;                                                    //没有显示记录条数   
        dbPage.OrderBy = "v_Product_goods.Goodsid,v_Product_goods.ProductCode,v_Product_goods.factor";                  //排序字段
        System.Data.IDataReader dr = dbPage.ExecuteReader();
        GridView1.DataSource = dr;
        GridView1.DataBind();
        //DlAttorney.DataSource = dr;
        //DlAttorney.DataBind();
        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键

    }
    public string fctConditions()
    {
        //string _strWhere = "bid_project_product.projectid=" + _strProjectId + " and Goods.Checkstatus=1 ";
        string _strWhere = "bid_goods_tbr.status=1 and bid_project_product.projectid=" + _strProjectId + " and bid_goods_tbr.accountid_tb=" + ((HZ.MBSM.Model.Account)Session["Account"]).AccountId + " and bid_goods_tbr.accountid_sc=" + _strAccountId_SC;

        //if (_strCompanySort == "1")
        //{
        //    //投标人如果是经营企业
        //    //_strWhere += " and Company.AccountId=" + _strAccountId_SC + "  and Goods.accountid_sc in (select accountid_sc from project_bid_company where accountid_tb=" + _strAccount_TBR + " and projectid=" + _strProjectId+")"; ;
        //    _strWhere += " and Company.AccountId=" + _strAccountId_SC;
        //}
        //else
        //{
        //    //投标人如果是生产企业
        //    _strWhere += " and Company.AccountId=" + _strAccount_TBR;
        //}
        //通用名
        string _strProductName = txtProductName.Text;
        if (_strProductName != "")
        {
            _strWhere += " and Product.ProductName like '%" + _strProductName + "%'";
        }
        //规格
        string _strOutLookc = txtOutlookc.Text;
        if (_strOutLookc != "")
        {
            _strWhere += " and Product.Outlookc like '%" + _strOutLookc + "%'";
        }

        //药品流水号
        string _strGoodsId = txtGoodsId.Text;
        if (_strGoodsId != "")
        {
            _strWhere += " and Goods.GoodsId=" + _strGoodsId;
        }
        return _strWhere;
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[12].Text == "1")//是否投标
            {
                e.Row.Cells[11].Text = "<input type=checkbox id=\"chk_" + e.Row.Cells[0].Text + "\" name=\"chk_" + e.Row.Cells[0].Text + "\" onclick=\"chk('" + e.Row.Cells[0].Text + "');\" checked=true />";//

            }
            else
            {
                e.Row.Cells[11].Text = "<input type=checkbox id=\"chk_" + e.Row.Cells[0].Text + "\" name=\"chk_" + e.Row.Cells[0].Text + "\" onclick=\"chk('" + e.Row.Cells[0].Text + "');\" />";//            
            }
        }
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[12].Visible = false;//是否投标
    }


    protected void submitbid()
    {
        if (_strAccount_TBR != "")
        {
            string[] sourcedata = txtdatabase.Value.Length == 0 ? new string[] { "" } : txtdatabase.Value.Substring(1).Split(new char[] { '@' });
            string[] modifydata = txtmsg.Value.Length == 0 ? new string[] { "" } : txtmsg.Value.Substring(1).Split(new char[] { '@' });
            string s = "";//保存所有操作的sql语句
            string _strDelGoodsId = "", _strInstGoodsId = "";
            //处理此次添加的投标商品
            string _strDataBase = txtdatabase.Value;
            for (int i = 0; i < modifydata.Length; i++)
            {
                //当 txtdatabase.Value="@173@731@1731@73" ，此时如果要对73号投标，
                //string _strTemp = "@" + modifydata[i];
                if (modifydata[i] != "")
                {
                    if (_strDataBase.Length == 0)
                    {//如果原来没有投过标,那么直接将所投记录插入到数据库中
                       // s += "@" + "insert Project_Bid(accountid,projectid,goodsid) values(" + _strAccount_TBR + "," + _strProjectId + "," + modifydata[i] + ")";
                        _strInstGoodsId += modifydata[i] + ",";
                    }
                    else
                    {//如果以前投过标,那么首先判断该条商品是否投过,如果投过就不需要向数据库中插入,如果没有投过就向数据库中插入记录
                        if (!_strDataBase.Contains("@" + modifydata[i] + "@"))
                        {//判断"@" + modifydata[i] + "@"是否已经在_strDataBase中,如:txtdatabase.Value="@173@731@1731"   modifydata[i] ="73"此时 "@" + modifydata[i] + "@"就不在_strDataBase中,那么继续执行if 里面的东西
                            if (_strDataBase.Contains("@" + modifydata[i]))
                            {//判断"@" + modifydata[i] 是否已经在_strDataBase中,如:txtdatabase.Value="@173@731@1731"   modifydata[i] ="73"
                                string _strTemp = _strDataBase.Substring(_strDataBase.Length - modifydata[i].Length - 1, modifydata[i].Length + 1);
                                if (_strTemp != "@" + modifydata[i])
                                {
                                   // s += "@" + "insert Project_Bid(accountid,projectid,goodsid) values(" + _strAccount_TBR + "," + _strProjectId + "," + modifydata[i] + ")";
                                    _strInstGoodsId += modifydata[i] + ",";
                                }
                            }
                            else
                            {
                                //s += "@" + "insert Project_Bid(accountid,projectid,goodsid) values(" + _strAccount_TBR + "," + _strProjectId + "," + modifydata[i] + ")";
                                _strInstGoodsId += modifydata[i] + ",";
                            }


                        }
                        //else
                        //{
                        //    s += "@" + "insert Project_Bid(accountid,projectid,goodsid) values(" + _strAccount_TBR + "," + _strProjectId + "," + modifydata[i] + ")";
                        //}
                    }
                }
            }

            if (_strInstGoodsId != "")
            {
                _strInstGoodsId = _strInstGoodsId.Substring(0, _strInstGoodsId.Length - 1);
                s += "@" + "insert Project_Bid(accountid,projectid,goodsid) select " + _strAccount_TBR + "," + _strProjectId +
                     ",goodsid from goods where checkstatus=1 and goodsid in (" + _strInstGoodsId + ") and goodsid not in (select goodsid from project_bid where goodsid in (" + _strInstGoodsId + ") and projectid=" + _strProjectId + " and accountid=" + _strAccount_TBR + ")";
            }

            //处理此次投标取消投标的商品
            //_strDel当前投标的品种 @7319@173
            //sourcedata 上一次投标的品种 @7319@173@73
            //判断那个流水号要删除,只要看看上一次投标的品种是否在本次的投标品种中就可以了.如果在就不用删除,如果不在就删除

            string _strDel = txtmsg.Value;
            for (int j = 0; j < sourcedata.Length; j++)
            {
                if (sourcedata[j] != "")
                {
                    if (_strDel.Length != 0)
                    {
                        //判断上次投标的流水号是否在当前投标记录中
                        if (!_strDel.Contains("@" + sourcedata[j] + "@"))
                        {//如果"@" + sourcedata[j] + "@"不在那么看看"@" + sourcedata[j] 是否在
                            if (_strDel.Contains("@" + sourcedata[j]))
                            {//如果在再判断是否是最后几个
                                string _strTemp = _strDel.Substring(_strDel.Length - sourcedata[j].Length - 1, sourcedata[j].Length + 1);
                                if (_strTemp != "@" + sourcedata[j])
                                {//如果不是删除
                                    _strDelGoodsId += sourcedata[j] + ",";
                                }
                            }
                            else
                            {//如果"@" + sourcedata[j]不在就删除
                                _strDelGoodsId += sourcedata[j] + ",";
                            }
                        }
                    }
                    else
                    {
                        _strDelGoodsId += sourcedata[j] + ",";
                    }
                }
            }

            //for (int j = 0; j < sourcedata.Length; j++)
            //{
            //    if (txtmsg.Value.Contains("@" + sourcedata[j]))
            //    {
            //        //不处理

            //    }
            //    else
            //    {
            //        //s += "@" + "delete from Project_Bid where accountid=" + _strAccount_TBR + " and projectid=" + _strProjectId + " and goodsid=" + sourcedata[j];
            //        _strDelGoodsId += sourcedata[j] + ",";
            //    }
            //}
            if (_strDelGoodsId != "")
            {
                s += "@" + "delete from Project_Bid where checkstatus=0 and accountid=" + _strAccount_TBR + " and projectid=" + _strProjectId + " and goodsid in (" + _strDelGoodsId.Substring(0, _strDelGoodsId.Length - 1) + ")";
            }

            Db db = new Db();
            bool succ=false;
            if (s.Length > 0)
            {
               succ= db.ExecuteTransaction(s.Substring(1).Split(new char[] { '@' }), 30);
            }
            else
            {
                return;
            }
            db.Close();
           
            txtdatabase.Value = "";
            txtmsg.Value = "";
            msg.Text = "";
            if(succ)
            {
                ClientScriptManager cs = Page.ClientScript;
                string cstext2 = "<script type=text/javascript>alert(\"投标成功!\");window.close();</script>";
                cs.RegisterClientScriptBlock(this.GetType(), "ButtonClickScript", cstext2, false);
            }
            else
            {
                ClientScriptManager cs = Page.ClientScript;
                string cstext2 = "<script type=text/javascript>alert(\"投标不成功,请等网络不忙时再投!\");</script>";
                cs.RegisterClientScriptBlock(this.GetType(), "ButtonClickScript", cstext2, false);
            }
          
        }

    }


    
}
